/* $Id: SimpleHttpServer.java 124 2010-09-23 16:25:36Z altdotua@gmail.com $ */

package djudge.utils;

import java.net.ServerSocket;
import java.net.Socket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;

import org.apache.log4j.Logger;

public class SimpleHttpServer
{
	private static final Logger log = Logger.getLogger(SimpleHttpServer.class);
	
	final SimpleHttpServerDataProvider dataProvider;
	
	public SimpleHttpServer(SimpleHttpServerDataProvider dataProvider, int port)
	{
		
		class SocketProcessor implements Runnable
		{
			private Socket s;
			private InputStream is;
			private OutputStream os;
			private SimpleHttpServerDataProvider dataProvider;

			private SocketProcessor(Socket s, SimpleHttpServerDataProvider prov) throws Throwable
			{
				this.dataProvider = prov;
				this.s = s;
				this.is = s.getInputStream();
				this.os = s.getOutputStream();
			}

			public void run()
			{
				try
				{
					readInputHeaders();
					writeResponse("");
				} catch (Throwable t)
				{
					/*do nothing*/
				} finally
				{
					try
					{
						s.close();
					} catch (Throwable t)
					{
						/*do nothing*/
					}
				}
				log.info("Client processing finished");
			}

			private void writeResponse(String s) throws Throwable
			{
				String response = "HTTP/1.1 200 OK\r\n"
						+ "Server: DJudge.http\r\n"
						+ "Content-Type: text/html\r\n" + "Content-Length: "
						+ s.length() + "\r\n" + "Connection: close\r\n\r\n";
				String result = response + dataProvider.getHtmlPage("");
				os.write(result.getBytes());
				os.flush();
			}

			private void readInputHeaders() throws Throwable
			{
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
				while (true)
				{
					String s = br.readLine();
					if (s == null || s.trim().length() == 0)
					{
						break;
					}
					log.debug(s);
				}
			}
		}
		
		
		this.dataProvider = dataProvider;
		try
		{
    		ServerSocket ss = new ServerSocket(port);
    		log.info("HttpServer started as " + port);
    		while (true)
    		{
    			Socket s = ss.accept();
    			log.info("Client accepted");
    			new Thread(new SocketProcessor(s, dataProvider)).start();
    		}
		}
		catch (Exception e)
		{
			
		}
		catch (Throwable e)
		{
			
		}
	}
	
}
